<template>
  <div>
    <PageWrapper :contentStyle="{ margin: '10px' }">
      <BasicTable @register="registerTable" :columns="columns" class="vipClassGrade m-l-10px">
        <template #action="{ record }">
          <TableAction
            v-if="editStatus && record.level === getDateValue.length - 1"
            :actions="[
              {
                label: t('common.delText'),
                color: 'error',
                ifShow: isHasAuth('10513'),
                onClick: showConfirm.bind(
                  null,
                  record,
                  'del',
                  $t('table.system.system_message_delete_tip'),
                ),
              },
            ]"
          />
          <TableAction
            class="vipTableAction"
            v-else-if="record.type === 'add'"
            :actions="[
              {
                label: t('common.saveText'),
                width: '50px',
                color: 'primary-color',
                onClick: saveAddData.bind(null, record),
              },
              {
                label: t('common.cancelText'),
                width: '50px',
                color: 'error',
                onClick: showConfirm.bind(
                  null,
                  record,
                  'cancel',
                  `${t('modalForm.member.member_cannot_be_restored_after_cancellation')}`,
                ),
              },
            ]"
          />
          <span v-else>-</span>
        </template>
        <template #tableTitle>
          <div>
            <div>
              <Space :size="10" class="t-form-label-com mt-2px">
                <Button type="primary" @click="editGrade" v-if="isHasAuth('10516')">
                  {{ $t('table.member.member_update_level') }}</Button
                >
                <Button @click="setVipUpdate" v-if="isHasAuth('10540')">{{
                  $t('table.member.member_rate_config')
                }}</Button>
                <Button @click="openScoreConfigModal" v-if="isHasAuth('10533')">{{
                  $t('table.member.member_points_config')
                }}</Button>
                <Button @click="openPrizeConfigModal" v-if="isHasAuth('10534')">{{
                  $t('table.member.member_bouns_condition')
                }}</Button>
                <Button @click="receive" v-if="isHasAuth('10515')">{{
                  $t('table.member.member_receive_record')
                }}</Button>
              </Space>
            </div>
            <div>
              <Space :size="10" class="t-form-label-com">
                <Button :type="configType === 1 ? 'primary' : ''" @click="selectConfigType(1)">{{
                  t('modalForm.system.system_basic_configuration')
                }}</Button>
                <Button
                  :type="configType === 2 ? 'primary' : ''"
                  @click="selectConfigType(2)"
                  v-if="isHasAuth('10520')"
                  >{{ t('modalForm.member.member_bonus_allocation') }}</Button
                >
              </Space>
            </div>
            <div v-if="configType === 2">
              <Space :size="10" class="mb-10px">
                <Tabs
                  v-model:tabValue="cashTypeId"
                  class="capsule_tap"
                  :destroyInactiveTabPane="true"
                  @change="selectTypeId"
                >
                  <TabPane v-for="item in typeItems" :tab="item.name" :key="item.id" />
                </Tabs>
              </Space>
            </div>
          </div>
        </template>
        <template #toolbar v-if="auths(['10512', '10513', '10514'])">
          <div v-if="!editStatus" :size="10" class="t-form-label-com toolbar-box">
            <Button @click="editDataSource">{{ t('common.editorText') }}</Button>
          </div>
          <div v-else class="toolbar-box save-toolbar-box">
            <Button
              class="savaButton"
              type="primary"
              v-if="isHasAuth('10512')"
              :disabled="disabledState"
              @click="editDataSave"
              >{{ t('common.saveText') }}</Button
            >
            <Button @click="editDataCancel" :disabled="disabledState">{{
              t('common.cancelText')
            }}</Button>
          </div>
        </template>
        <template #memberNumber="{ record }">
          <router-link
            v-if="record.total > 0 && isHasAuth('10100')"
            :to="{
              path: '/member/inquiryMember',
              query: { vipLevel: String(record.level) },
            }"
            class="member-number"
            >{{ record.total }}
          </router-link>
          <span v-else-if="record.total > 0 && !isHasAuth('10100')">{{ record.total }}</span>
          <span v-else>0</span>
        </template>
        <template #headerCell="{ column }">
          <div v-if="column.editComponent === 'InputNumber' && isCurrencyTitle(column.dataIndex)">
            {{ handelCurrencyTitle(column.customTitle) }}
            <cdIconCurrency :icon="isCurrencyTitle(column.dataIndex)" class="w-22px" />
            {{ isCurrencyTitle(column.dataIndex) }}
          </div>
          <div v-else>{{ column.customTitle }}</div>
        </template>
      </BasicTable>
      <Button
        class="add-creat-vip"
        v-if="editStatus && configType === 1 && isHasAuth('10514')"
        :disabled="disabledState"
        shape="round"
        @click="handleAdd"
      >
        <template #icon>
          <img :src="addVipDegreePng" class="!w-18px btn-icon" />
        </template>
        {{ t('business.add_new') }}VIP</Button
      >
    </PageWrapper>
    <EditGrade @register="registerEditModal" />
    <Receive @register="registerReceive" />
    <vipConfigModal @register="registerVipConfig" />
    <ScoreConfigModal @register="registerScoreConfig" />
    <PrizeConditionModal @register="registerPrizeConfig" />
    <newRebateModal @register="registerRebateModal" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { auths, isHasAuth } from '@/utils/authFunction';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { basicColumn, upgradeColumn, monthColumn, weekColumn, dayColumn } from './vipGrade.data';
  import { Space, Button, message, Tabs, TabPane } from 'ant-design-vue';
  import { openConfirm } from '/@/utils/confirm';
  import { useModal } from '/@/components/Modal';
  import Receive from './components/Receive.vue';
  import EditGrade from './components/EditGrade.vue';
  import vipConfigModal from './components/vipConfigModal.vue';
  import ScoreConfigModal from './components/ScoreConfigModal.vue';
  import PrizeConditionModal from './components/PrizeConditionModal.vue';
  import newRebateModal from './components/newRebateModal.vue';
  import { ScrollActionType } from '/@/components/Container/index';
  import { type Nullable } from '@vben/types';
  import {
    getVipLevelList,
    getPrizeLevelList,
    deleteBasicVip,
    updateVipBase,
    updateVipPrize,
    insertBaseVip,
  } from '@/api/member/index';
  import addVipDegreePng from '/@/assets/images/add-vip-degree.webp';
  import { useCurrencyStore } from '/@/store/modules/currency';
  import cdIconCurrency from '/@/components-cd/Icon/currency/cd-icon-currency.vue';

  const scrollRef = ref<Nullable<ScrollActionType>>(null);
  const getScroll = () => {
    const scroll = unref(scrollRef);
    if (!scroll) {
      throw new Error('scroll is Null');
    }
    return scroll;
  };
  const [registerEditModal, { openModal: openEdit }] = useModal();
  const [registerVipConfig] = useModal();
  const [registerScoreConfig, { openModal: openScoreConfig }] = useModal();
  const [registerPrizeConfig, { openModal: openPrizeConfig }] = useModal();
  const [registerReceive, { openModal: openReceive }] = useModal();
  const [registerRebateModal, { openModal: openModalRebate }] = useModal();
  const editStatus = ref(false as any);
  const getDateValue = ref([] as any);
  const disabledState = ref(false as any);
  const setHeight = ref(1000 as any);
  const { getAllCurrencyList } = useCurrencyStore();
  /** 更新VIP等级 */
  function editGrade() {
    openEdit(true, 'data');
  }
  /** 领取记录 */
  function receive() {
    openReceive(true, 'data');
  }
  /** 积分配置 */
  function openScoreConfigModal() {
    openScoreConfig(true, 'data');
  }
  /** 积分条件 */
  function openPrizeConfigModal() {
    openPrizeConfig(true, 'data');
  }
  /** 返水配置 */
  function setVipUpdate() {
    openModalRebate(true, 'data');
  }

  const { t } = useI18n();
  let columns = ref<Object[]>(basicColumn);
  /** 配置类型 */
  const configType = ref<number>(1);
  /** 奖金配置选项 */
  interface TypeItem {
    id: String;
    name: String;
  }
  /** 奖金类型选项 */
  const typeItems = ref<TypeItem[]>([
    { id: '818', name: t('table.member.member_promotion_gift') },
    { id: '821', name: t('table.member.member_every_month') },
    { id: '820', name: t('table.member.member_every_week') },
    { id: '819', name: t('table.member.member_every_day') },
  ]);
  /** 奖金类型Id */
  const cashTypeId = ref<string>('818');
  /** 选择奖金类型 */
  function selectTypeId(activeKey) {
    cashTypeId.value = activeKey;
    editStatus.value = false;
    if (configType.value === 1) {
      columns.value = basicColumn;
    } else {
      switch (cashTypeId.value) {
        case '818':
          columns.value = upgradeColumn;
          reload();
          return;
        case '821':
          columns.value = monthColumn;
          reload();
          return;
        case '820':
          columns.value = weekColumn;
          reload();
          return;
        case '819':
          columns.value = dayColumn;
          reload();
          return;
        default:
          columns.value = [];
          return;
      }
    }
  }
  /** 获取基础配置列表 */
  async function getBasicData() {
    const data = await getVipLevelList();
    let dataSource = data.filter((item) => item.is_delete === 2);
    getDateValue.value = dataSource;
    return dataSource;
  }
  /** 获取奖金配置列表 */
  const getPrizeData = async () => {
    const data = await getPrizeLevelList({ cash_type: cashTypeId.value });
    return data;
  };
  const getTableData = async () => {
    if (configType.value === 1) {
      return getBasicData();
    } else {
      return getPrizeData();
    }
  };
  /** 表格数据 */
  const [registerTable, { getDataSource, reload, redoHeight }] = useTable({
    api: getTableData,
    pagination: false,
    showIndexColumn: false,
    bordered: true,
  });
  /** 选择配置类型 */
  function selectConfigType(typeid: number) {
    // console.log(111,configType.value,typeid)
    if (configType.value == typeid) return;
    configType.value = typeid;
    editStatus.value = false;
    if (configType.value === 1) {
      columns.value = basicColumn;
    } else {
      columns.value = upgradeColumn;
    }

    reload();
  }
  /**新增VIP */
  function handleAdd() {
    const data = getDataSource();
    data.push({
      level: data.length,
      total: 0,
      upgrade: '0',
      retain: '0',
      multiple: '0',
      type: 'add',
    } as never);
    disabledState.value = true;
    setTimeout(() => {
      //console.log(data.length * 30);
      data[data.length - 1].onEdit?.(true);
      setHeight.value = redoHeight();
    }, 500);
  }
  /** 确认删除 */
  function showConfirm(record, type, msg) {
    openConfirm(t('modalForm.finance.finance_operation_confirmation'), msg, async () => {
      if (type === 'status') {
        const { data, status } = await deleteBasicVip({
          level: record.level,
        });
        if (status) {
          message.success(data);
          disabledState.value = false;
        } else {
          message.error(data);
        }
      } else if (type === 'del') {
        const { data, status } = await deleteBasicVip({
          level: record.level,
        });
        if (status) {
          message.success(data);
          editStatus.value = false;
        } else {
          message.error(data);
        }
      } else if (type === 'cancel') {
        const data = getDataSource();
        data.pop();
        disabledState.value = false;
      }
      reload();
    });
  }
  //单条保存
  async function saveAddData(record) {
    console.log(record);
    const params = {
      level: record.level,
      total: record.total,
      upgrade: String(record.editValueRefs.upgrade),
      retain: String(record.editValueRefs.retain),
      multiple: String(record.editValueRefs.multiple),
    };
    if (
      Number(record.editValueRefs.upgrade) === 0 &&
      Number(record.editValueRefs.retain) === 0 &&
      Number(record.editValueRefs.multiple) === 0
    ) {
      message.error(t('modalForm.member.member_cannot_be_all0'));
      return;
    }
    const { status, data } = await insertBaseVip(params);
    if (status) {
      message.success(data);
      editStatus.value = false;
      disabledState.value = false;
      reload();
      getScroll()?.scrollTo(0);
    }
  }
  function editDataSource() {
    const data = getDataSource();
    // console.log('223',isHasAuth('10512'),data);
    if (isHasAuth('10512')) {
      data.forEach((item: any) => {
        item.onEdit?.(true);
      });
    }
    editStatus.value = true;
  }

  function editDataCancel() {
    const data = getDataSource();
    console.log(data);
    data.forEach((item: any) => {
      item.onEdit?.(false, false);
    });
    editStatus.value = false;
  }
  //判断表格标题是否是货币
  function isCurrencyTitle(title) {
    if (title == 'vnd') title = 'kvnd';
    title = title.toUpperCase();
    let hasCurrency = getAllCurrencyList.filter((c) => c.name === title);
    return hasCurrency.length > 0 ? title : false;
  }

  function handelCurrencyTitle(title) {
    return title.split('(')[0];
  }

  async function editDataSave() {
    const getDataModal = getDataSource();
    console.log(getDataModal);
    console.log('configType.value', configType.value);
    let getDate: Array<any> = [];
    if (configType.value === 1) {
      getDate = getDataModal.map((item: any) => {
        if (item.editValueRefs) {
          return {
            is_default: item.is_default,
            total: item.total,
            level: item.level,
            upgrade: String(item.editValueRefs.upgrade),
            retain: String(item.editValueRefs.retain),
            multiple: String(item.editValueRefs.multiple),
          };
        } else {
          return {
            is_default: item.is_default,
            total: item.total,
            level: item.level,
            upgrade: String(item.upgrade),
            retain: String(item.retain),
            multiple: String(item.multiple),
            created_at: 0,
            updated_at: 0,
          };
        }
      });
      const { data, status } = await updateVipBase(getDate);
      if (status) {
        message.success(data);
        console.log('成功');
        reload();
        editDataCancel();
        editStatus.value = false;
      }
    } else if (configType.value === 2) {
      getDate = getDataModal.map((item: any) => {
        if (item.editValueRefs) {
          return {
            level: item.level,
            deposit_amount: '0.00',
            valid_bet_amount: '0.00',
            cash_type: Number(cashTypeId.value),
            usdt: String(item.editValueRefs.usdt),
            brl: String(item.editValueRefs.brl),
            cny: String(item.editValueRefs.cny),
            kvnd: String(item.editValueRefs.kvnd),
            thb: String(item.editValueRefs.thb),
            inr: String(item.editValueRefs.inr),
          };
        } else {
          return {
            deposit_amount: '0.00',
            valid_bet_amount: '0.00',
            cash_type: Number(cashTypeId.value),
            level: item.level,
            usdt: String(item.usdt),
            brl: String(item.brl),
            cny: String(item.cny),
            kvnd: String(item.kvnd),
            thb: String(item.thb),
            inr: String(item.inr),
          };
        }
      });
      const { data, status } = await updateVipPrize(getDate);
      if (status) {
        message.success(data);
        console.log('成功');
        reload();
        editDataCancel();
        editStatus.value = false;
      }
    }

    console.log(getDate);
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-input-number-input) {
    text-align: center;
  }

  ::v-deep(.toolbar-box .savaButton[disabled]) {
    border: 1px solid #e1e1e1 !important;
    background: #f5f5f5 !important;
  }

  .vipgrade {
    padding: 10px 0;
  }

  .add-creat-vip {
    width: 122px !important;
    height: 42px !important;
    margin-top: 10px;
    margin-left: calc(50% - 61px);
    border-radius: 42px !important;
    border-color: #1475e1;
    background-color: #1475e1;
    color: #fff;
    font-size: 22px !important;
  }

  ::v-deep(.ant-table) {
    background-color: transparent !important;
  }

  ::v-deep(.ant-btn) {
    //width: 120px;
    height: 42px;
    //padding: 0 !important;
    border: 1px solid #e1e1e1 !important;
    box-shadow: none !important;
    font-size: 14px !important;
    font-weight: 500 !important;

    &.ant-btn-primary {
      border: 1px solid #1475e1 !important;
      background-color: #1475e1 !important;
    }
  }

  ::v-deep(.vben-basic-table .ant-table-wrapper .ant-table-title) {
    padding-bottom: 0 !important;
  }

  ::v-deep(.ant-table-container) {
    th {
      height: 62px !important;
    }

    tr:not(:first-child) > td {
      height: 62px !important;
    }
  }

  ::v-deep(.ant-input-number-input) {
    height: 40px !important;
  }

  ::v-deep(.ant-table.ant-table-middle .ant-table-tbody > tr > td) {
    padding: 8px 6px;
  }

  ::v-deep(.vben-basic-table-header__tableTitle > *) {
    margin-bottom: 0 !important;
  }

  ::v-deep(.ant-tabs-top > .ant-tabs-nav) {
    margin-top: 0 !important;
    margin-bottom: 0 !important;
  }

  .toolbar-box {
    display: flex;
    position: absolute;
    margin-right: 0 !important;

    button {
      margin-left: 10px !important;
    }
  }

  .save-toolbar-box {
    button {
      width: 74px !important;
    }
  }

  .member-number {
    color: #409eff;
  }

  .btn-icon {
    margin-top: -2px !important;
    margin-right: 5px;
  }

  ::v-deep(.ant-btn-link) {
    border: none !important;
    text-align: center !important;

    span {
      width: 100%;
      text-align: center !important;
    }

    &::v-deep(.ant-btn-error) {
      span {
        color: #e91134 !important;
      }
    }
  }

  ::v-deep(.vipClassGrade .ant-table-body .ant-table-tbody .ant-table-cell > div) {
    width: 100% !important;
  }

  ::v-deep(.vipClassGrade .ant-table-row:nth-of-type(odd)) {
    background-color: #f6f7fb !important;
  }

  //
  ::v-deep(.vipClassGrade .ant-table-row:nth-of-type(even)) {
    background-color: #fff !important;
  }

  ::v-deep(.vipClassGrade .ant-table-row:nth-of-type(even) > .ant-table-cell-row-hover) {
    background-color: transparent !important;
  }

  ::v-deep(.vipClassGrade .ant-table-row:nth-of-type(odd) > .ant-table-cell-row-hover) {
    background-color: transparent !important;
  }

  :deep(.vipTableAction) {
    .ant-btn {
      width: 50px;
    }
  }
</style>
